<template>
	<view class="page-container" :style="{
	  '--button-x': `${buttonPosition.x}px`,
	  '--button-y': `${buttonPosition.y}px`
	}">
		<!-- 顶部搜索区域 -->
		<view class="search-section">
			<uni-search-bar v-model="searchText" placeholder="搜索农田名称/位置" radius="100" bgColor="#f5f5f5"
				clearButton="auto" @confirm="handleSearch" @clear="clearSearch" />
		</view>

		<!-- 用户统计信息 -->
		<view class="stats-section" v-if="isLoggedIn && userStats">
			<view class="stat-item">
				<text>本月新增: {{ userStats.monthlyCount }}</text>
			</view>
			<view class="stat-item">
				<text>总计新增: {{ userStats.totalCount }}</text>
			</view>
		</view>

		<!-- 筛选功能区 -->
		<scroll-view class="filter-section" scroll-x>
			<view class="filter-tags">
				<view v-for="(tag, index) in filterTags" :key="index"
					:class="['filter-tag', { active: activeFilter === tag.value }]"
					@click="handleFilterChange(tag.value)">
					{{ tag.label }}
				</view>
			</view>
		</scroll-view>

		<!-- 农田列表区域 -->
		<scroll-view class="farm-list" scroll-y>
			<view v-for="(farm, index) in filteredFarms" :key="index" class="farm-card"
				@click="handleFarmClick(farm.id)">
				<view class="farm-card-content">
					<image class="crop-image" :src="getImageUrl(farm.imageUrl)" mode="aspectFill" />
					<view class="farm-info">
						<view class="farm-name">{{ farm.name }}</view>
						<view class="farm-location">
							<uni-icons type="location-filled" size="14" color="#999" />
							<text>{{ farm.location }}</text>
						</view>
						<view class="farm-status">
							<view class="status-tag" :style="{ backgroundColor: getStatusColor(farm.status) }">
								{{ farm.status }}
							</view>
							<text class="crop-name">{{ farm.crop }}</text>
						</view>
					</view>
				</view>
				<view class="farm-footer">
					<text class="update-time">最近更新: {{ formatUpdateTime(farm.updateTime) }}</text>
					<view class="quick-actions">
						<view class="action-btn" @click.stop="handleStatusMark(farm.id)">
							<uni-icons type="trash" size="16" color="#666" />
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部添加按钮 -->
		<view class="add-button-float" :class="{ 'button-active': isButtonActive }" @touchstart="handleButtonTouchStart"
			@touchmove="handleButtonTouchMove" @touchend="handleButtonTouchEnd" @click="handleAddFarm"
			v-if="isLoggedIn">
			<view class="button-inner">
				<uni-icons type="plus-filled" size="24" color="#fff" />
			</view>
		</view>

		<!-- 添加新农田弹窗 -->
		<uni-popup ref="addPopup" type="bottom" :mask-click="false">
			<view class="add-farm-form">
				<view class="form-title">添加新农田</view>
				<uni-forms ref="addForm" :modelValue="newFarm">
					<uni-forms-item label="农田名称" name="name" required>
						<uni-easyinput v-model="newFarm.name" placeholder="请输入农田名称" />
					</uni-forms-item>
					<uni-forms-item label="位置" name="location" required>
						<uni-easyinput v-model="newFarm.location" placeholder="请输入农田位置" />
					</uni-forms-item>
					<uni-forms-item label="作物" name="crop" required>
						<uni-easyinput v-model="newFarm.crop" placeholder="请输入种植作物" />
					</uni-forms-item>
					<uni-forms-item label="状态" name="status" required>
						<uni-data-select v-model="newFarm.status" :localdata="statusOptions" />
					</uni-forms-item>
					<uni-forms-item label="农田图片" name="imageUrl">
						<uni-file-picker v-model="newFarm.imageFiles" fileMediatype="image" limit="1"
							:image-styles="imageStyles" @success="handleImageSelect" @delete="handleImageDelete" />
					</uni-forms-item>
					<view class="form-buttons">
						<button class="cancel-btn" @click="cancelAddFarm">取消</button>
						<button class="submit-btn" @click="submitAddFarm">确认添加</button>
					</view>
				</uni-forms>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';

	// API 基础URL
	const API_BASE = 'http://localhost:3000';

	// 组件引用
	const addPopup = ref();
	const addForm = ref();

	// 数据状态
	const farms = ref([]);
	const isLoading = ref(false);
	const filterTags = ref([{
			value: 'all',
			label: '全部'
		},
		{
			value: 'sowing',
			label: '播种期'
		},
		{
			value: 'growing',
			label: '生长期'
		},
		{
			value: 'irrigation',
			label: '需灌溉'
		},
		{
			value: 'fertilization',
			label: '需施肥'
		}
	]);
	const statusOptions = ref([{
			value: '播种期',
			text: '播种期'
		},
		{
			value: '生长期',
			text: '生长期'
		},
		{
			value: '需灌溉',
			text: '需灌溉'
		},
		{
			value: '需施肥',
			text: '需施肥'
		}
	]);
	const activeFilter = ref('all');
	const isLoggedIn = ref(false);
	const currentUserId = ref(null);
	const currentMonth = ref(new Date().toISOString().slice(0, 7));
	const userStats = ref({
		totalCount: 0,
		monthlyCount: 0
	});

	// 新农田数据
	const newFarm = ref({
		name: '',
		location: '',
		crop: '',
		status: '播种期',
		imageFiles: [],
		imageUrl: ''
	});

	// 图片样式
	const imageStyles = {
		width: 160,
		height: 160,
		border: {
			color: "#eee",
			width: "1px",
			style: "solid"
		}
	};

	// 搜索相关状态
	const searchText = ref('');

	// 检查登录状态
	const checkLoginStatus = () => {
		try {
			const userinfo = JSON.parse(sessionStorage.getItem('userinfo') || '{}');
			isLoggedIn.value = !!userinfo.userId;
			currentUserId.value = userinfo.userId || null;
		} catch (e) {
			console.error('解析用户信息失败:', e);
			isLoggedIn.value = false;
			currentUserId.value = null;
		}
	};

	// 获取正确的图片URL
	const getImageUrl = (url) => {
		if (!url) return '/static/images/default-farm.jpg';
		if (typeof url === 'object' && url.url) return url.url;
		if (url.startsWith('http') || url.startsWith('/')) return url;
		return `/static/images/${url}`;
	};

	// 格式化更新时间
	const formatUpdateTime = (timeString) => {
		return timeString || '';
	};

	// 加载数据
	const loadData = () => {
		checkLoginStatus();

		// 加载农田数据
		let farmUrl = `${API_BASE}/farms`;
		if (isLoggedIn.value && currentUserId.value) {
			farmUrl += `?userId=${currentUserId.value}`;
		}

		uni.request({
			url: farmUrl,
			success: (res) => {
				farms.value = (res.data || []).map(farm => ({
					...farm,
					imageUrl: getImageUrl(farm.imageUrl)
				}));
			},
			fail: (err) => {
				console.error('加载农田数据失败:', err);
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				});
			}
		});

		// 加载用户统计
		if (isLoggedIn.value && currentUserId.value) {
			loadUserStats();
		}
	};

	// 加载用户统计
	const loadUserStats = () => {
		uni.request({
			url: `${API_BASE}/users/${currentUserId.value}`,
			success: (res) => {
				const stats = res.data?.farmStats || {
					totalAdded: 0,
					monthlyAdded: []
				};

				userStats.value = {
					totalCount: stats.totalAdded || 0,
					monthlyCount: stats.monthlyAdded?.find(
						m => m.month === currentMonth.value
					)?.count || 0
				};
			},
			fail: (err) => {
				console.error('加载用户统计失败:', err);
				userStats.value = {
					totalCount: 0,
					monthlyCount: 0
				};
			}
		});
	};

	// 减少用户统计计数
	const decrementUserStats = () => {
		uni.request({
			url: `${API_BASE}/users/${currentUserId.value}`,
			success: (userRes) => {
				const user = userRes.data || {};
				user.farmStats = user.farmStats || {
					totalAdded: 0,
					monthlyAdded: []
				};

				// 确保不会减到负数
				user.farmStats.totalAdded = Math.max(0, (user.farmStats.totalAdded || 0) - 1);

				// 更新月度统计
				const monthIndex = user.farmStats.monthlyAdded?.findIndex(
					m => m.month === currentMonth.value
				) ?? -1;

				if (monthIndex >= 0) {
					user.farmStats.monthlyAdded[monthIndex].count =
						Math.max(0, user.farmStats.monthlyAdded[monthIndex].count - 1);
				}

				// 保存更新
				uni.request({
					url: `${API_BASE}/users/${currentUserId.value}`,
					method: 'PUT',
					data: user,
					success: () => {
						loadUserStats(); // 刷新统计显示
					},
					fail: (err) => {
						console.error('更新统计失败:', err);
						loadUserStats(); // 仍然尝试刷新
					}
				});
			},
			fail: (err) => {
				console.error('获取用户数据失败:', err);
			}
		});
	};

	// 根据筛选条件过滤农田列表
	const filteredFarms = computed(() => {
		let filteredList = [];

		// 第一步：根据状态筛选
		if (activeFilter.value === 'all') {
			filteredList = [...farms.value];
		} else {
			filteredList = farms.value.filter(farm => {
				switch (activeFilter.value) {
					case 'sowing':
						return farm.status === '播种期';
					case 'growing':
						return farm.status === '生长期';
					case 'irrigation':
						return farm.status === '需灌溉';
					case 'fertilization':
						return farm.status === '需施肥';
					default:
						return true;
				}
			});
		}

		// 第二步：根据搜索文本筛选
		const searchTerm = searchText.value.trim().toLowerCase();
		if (searchTerm) {
			filteredList = filteredList.filter(farm => {
				const nameMatch = farm.name && farm.name.toLowerCase().includes(searchTerm);
				const locationMatch = farm.location && farm.location.toLowerCase().includes(searchTerm);
				return nameMatch || locationMatch;
			});
		}

		return filteredList;
	});

	// 获取状态标签颜色
	const getStatusColor = (status) => {
		switch (status) {
			case '播种期':
				return '#95d475';
			case '生长期':
				return '#4caf50';
			case '需灌溉':
				return '#64b5f6';
			case '需施肥':
				return '#ffb74d';
			default:
				return '#9e9e9e';
		}
	};

	// 处理筛选条件变化
	const handleFilterChange = (value) => {
		activeFilter.value = value;
	};

	// 根据id进页面详情页
	const handleFarmClick = (id) => {
		uni.navigateTo({
			url: `/pages/farmDetail/farmDetail?id=${id}`
		});
	};

	// 处理删除农田
	const handleStatusMark = (id) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这块农田吗？',
			success: (res) => {
				if (res.confirm) {
					isLoading.value = true;
					uni.request({
						url: `${API_BASE}/farms/${id}`,
						method: 'DELETE',
						success: () => {
							// 先减少统计
							decrementUserStats();
							// 然后刷新列表
							loadData();
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						},
						fail: (err) => {
							console.error('删除失败:', err);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						},
						complete: () => {
							isLoading.value = false;
						}
					});
				}
			}
		});
	};

	// 处理添加农田
	const handleAddFarm = () => {
		if (!isLoggedIn.value) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			return;
		}
		uni.hideTabBar();
		addPopup.value.open();
	};

	// 处理图片选择
	const handleImageSelect = (e) => {
		newFarm.value.imageFiles = e.tempFiles;
		newFarm.value.imageUrl = e.tempFiles[0]?.path || '';
	};

	// 处理图片删除
	const handleImageDelete = () => {
		newFarm.value.imageFiles = [];
		newFarm.value.imageUrl = '';
	};

	// 添加农田提交
	const submitAddFarm = async () => {
		try {
			await addForm.value.validate();

			if (!isLoggedIn.value || !currentUserId.value) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}

			// 生成格式化的时间字符串
			const now = new Date();
			const formattedTime =
				`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

			const farmData = {
				...newFarm.value,
				userId: currentUserId.value,
				updateTime: formattedTime,
				imageUrl: newFarm.value.imageUrl || '/static/images/farmdetail4.jpg'
			};

			// 删除不需要的字段
			delete farmData.imageFiles;

			isLoading.value = true;
			uni.request({
				url: `${API_BASE}/farms`,
				method: 'POST',
				data: farmData,
				success: (res) => {
					// 更新用户统计
					updateUserStats();
					uni.showTabBar();
				},
				fail: (err) => {
					console.error('添加农田失败:', err);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				},
				complete: () => {
					isLoading.value = false;
				},


			});
		} catch (e) {
			console.error('表单验证失败:', e);
		}
	};

	// 更新用户统计（增加）
	const updateUserStats = () => {
		const now = new Date();
		currentMonth.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
		uni.request({
			url: `${API_BASE}/users/${currentUserId.value}`,
			success: (userRes) => {
				const user = userRes.data || {};
				user.farmStats = user.farmStats || {
					totalAdded: 0,
					monthlyAdded: []
				};

				// 更新统计
				user.farmStats.totalAdded = (user.farmStats.totalAdded || 0) + 1;

				const monthIndex = user.farmStats.monthlyAdded?.findIndex(
					m => m.month === currentMonth.value
				) ?? -1;

				if (monthIndex >= 0) {
					user.farmStats.monthlyAdded[monthIndex].count += 1;
				} else {
					user.farmStats.monthlyAdded.push({
						month: currentMonth.value,
						count: 1
					});
				}

				// 保存更新
				uni.request({
					url: `${API_BASE}/users/${currentUserId.value}`,
					method: 'PUT',
					data: user,
					success: () => {
						loadData();
						addPopup.value.close();
						resetForm();
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						console.error('更新统计失败:', err);
						loadData();
						addPopup.value.close();
						resetForm();
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
					}
				});
			},
			fail: (err) => {
				console.error('获取用户数据失败:', err);
				loadData();
				addPopup.value.close();
				resetForm();
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
			}
		});
	};

	// 重置表单
	const resetForm = () => {
		newFarm.value = {
			name: '',
			location: '',
			crop: '',
			status: '播种期',
			imageFiles: [],
			imageUrl: ''
		};
	};

	// 取消添加
	const cancelAddFarm = () => {
		uni.showTabBar();
		addPopup.value.close();
		resetForm();
		loadData();
	};

	// 悬浮球相关状态
	const isButtonActive = ref(false);
	const buttonPosition = ref({
		x: 0,
		y: 0,
		startX: 0,
		startY: 0
	});

	// 获取屏幕尺寸
	const screenWidth = ref(0);
	const screenHeight = ref(0);

	onMounted(() => {
		loadData();
		// 获取屏幕尺寸
		const systemInfo = uni.getSystemInfoSync();
		screenWidth.value = systemInfo.windowWidth;
		screenHeight.value = systemInfo.windowHeight;

		// 初始位置（右下角）
		buttonPosition.value.x = screenWidth.value - 80;
		buttonPosition.value.y = screenHeight.value - 180;
	});

	// 触摸开始
	const handleButtonTouchStart = (e) => {
		isButtonActive.value = true;
		buttonPosition.value.startX = e.touches[0].clientX;
		buttonPosition.value.startY = e.touches[0].clientY;
	};

	// 触摸移动
	const handleButtonTouchMove = (e) => {
		if (!isButtonActive.value) return;

		const currentX = e.touches[0].clientX;
		const currentY = e.touches[0].clientY;

		// 计算移动距离
		const deltaX = currentX - buttonPosition.value.startX;
		const deltaY = currentY - buttonPosition.value.startY;

		// 更新位置
		buttonPosition.value.x += deltaX;
		buttonPosition.value.y += deltaY;

		// 限制在屏幕范围内
		buttonPosition.value.x = Math.max(0, Math.min(buttonPosition.value.x, screenWidth.value - 80));
		buttonPosition.value.y = Math.max(0, Math.min(buttonPosition.value.y, screenHeight.value - 80));

		// 更新起始位置
		buttonPosition.value.startX = currentX;
		buttonPosition.value.startY = currentY;
	};

	// 触摸结束
	const handleButtonTouchEnd = () => {
		isButtonActive.value = false;

		// 吸附到边缘
		if (buttonPosition.value.x > screenWidth.value / 2) {
			buttonPosition.value.x = screenWidth.value - 80;
		} else {
			buttonPosition.value.x = 0;
		}
	};

	// 搜索处理函数
	const handleSearch = () => {
		// 搜索逻辑已经在计算属性filteredFarms中实现
		// 这里可以添加额外的搜索逻辑（如远程搜索）如果需要
	};

	// 清除搜索
	const clearSearch = () => {
		searchText.value = '';
	};
</script>

<style>
	page {
		height: 100%;
		background-color: #f7f7f7;
	}

	.page-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		padding-bottom: 120rpx;
	}

	/* 搜索区域 */
	.search-section {
		padding: 20rpx 30rpx;
		background-color: #fff;
	}

	/* 统计信息区域 */
	.stats-section {
		display: flex;
		padding: 15rpx 30rpx;
		background-color: #f9f9f9;
		border-bottom: 1rpx solid #eee;
	}

	.stat-item {
		margin-right: 30rpx;
		font-size: 14px;
		color: #666;
	}

	/* 筛选功能区 */
	.filter-section {
		background-color: #fff;
		padding: 20rpx 0;
		white-space: nowrap;
	}

	.filter-tags {
		display: inline-flex;
		align-items: center;
		padding: 0 30rpx;
	}

	.filter-tag {
		display: inline-flex;
		padding: 10rpx 24rpx;
		margin-right: 20rpx;
		border-radius: 40rpx;
		font-size: 12px;
		color: #666;
		background-color: #f5f5f5;
	}

	.filter-tag.active {
		color: #fff;
		background-color: #4caf50;
	}

	/* 农田列表 */
	.farm-list {
		box-sizing: border-box;
		width: 100%;
		flex: 1;
		padding: 20rpx 30rpx;
		overflow: auto;
	}

	.farm-card {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.farm-card-content {
		display: flex;
		padding: 20rpx;
	}

	.crop-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.farm-info {
		flex: 1;
	}

	.farm-name {
		font-size: 16px;
		font-weight: 500;
		color: #333;
		margin-bottom: 10rpx;
	}

	.farm-location {
		display: flex;
		align-items: center;
		font-size: 12px;
		color: #999;
		margin-bottom: 20rpx;
	}

	.farm-location text {
		margin-left: 6rpx;
	}

	.farm-status {
		display: flex;
		align-items: center;
	}

	.status-tag {
		padding: 4rpx 12rpx;
		border-radius: 4rpx;
		font-size: 12px;
		color: #fff;
		margin-right: 12rpx;
	}

	.crop-name {
		font-size: 14px;
		color: #666;
	}

	.farm-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 20rpx;
		border-top: 1rpx solid #f5f5f5;
	}

	.update-time {
		font-size: 12px;
		color: #999;
	}

	.quick-actions {
		display: flex;
	}

	.action-btn {
		padding: 8rpx;
	}

	/* 添加新农田样式 */
	.add-farm-form {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 20rpx 20rpx 0 0;
	}

	.form-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.form-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.cancel-btn {
		flex: 1;
		margin-right: 20rpx;
		background-color: #f5f5f5;
		color: #666;
	}

	.submit-btn {
		flex: 1;
		background-color: #4caf50;
		color: #fff;
	}

	/* 确保表单项目有适当的间距 */
	.uni-forms-item {
		margin-bottom: 20rpx;
	}

	/* 添加图片上传组件的样式 */
	.uni-file-picker {
		width: 100%;
	}

	.uni-file-picker__header {
		display: none;
	}

	/* 动态悬浮按钮 */
	.add-button-float {
		position: fixed;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #4caf50;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
		z-index: 100;
		transition: transform 0.2s ease, background-color 0.2s ease;
		transform: translate3d(var(--button-x), var(--button-y), 0);
	}

	.add-button-float.button-active {
		transform: translate3d(var(--button-x), var(--button-y), 0) scale(1.1);
		background-color: #3d8b40;
	}

	.button-inner {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
	}
</style>